package cool.taomu.box.tomcat

import com.google.inject.name.Named
import com.google.inject.servlet.GuiceServletContextListener
import java.io.File
import javax.inject.Inject
import javax.servlet.Servlet
import org.apache.catalina.Context
import org.apache.catalina.LifecycleException
import org.apache.catalina.startup.Tomcat
import org.slf4j.LoggerFactory

interface ITomcatServer {
	def void start()
}

class TomcatServer implements ITomcatServer {
	val LOG = LoggerFactory.getLogger(TomcatServer);

	@Inject
	Servlet servlet;

	@Inject
	ITomcatFilter ifilter;

	@Inject
	@Named("port")
	int port

	override start() {
		var File base = new File(System.getProperty("java.io.tmpdir"));
		val tomcat = new Tomcat();
		Runtime.getRuntime().addShutdownHook(
			new Thread([
				try {
					tomcat.destroy();
				} catch (LifecycleException e) {
					e.printStackTrace();
				}
			])
		);
		tomcat.port = port;
		tomcat.connector;
		val ctx = tomcat.addContext("/", base.absolutePath);
		addFilter(ctx);
		var wrapper = Tomcat.addServlet(ctx, "base", servlet);
		tomcat.start();
		wrapper.setLoadOnStartup(1);
		wrapper.addMapping("/");
		tomcat.server.await();
	}

	protected def void addFilter(Context ctx) {
		if (ifilter !== null) {
			this.ifilter.filterDefs.filterNull.forEach [
				LOG.info("Filter def :{}", it.filterName);
				ctx.addFilterDef(it)
			]
			this.ifilter.filterMaps.filterNull.forEach [
				LOG.info("Filter map :{}", it.filterName);
				ctx.addFilterMap(it)
			]
			this.ifilter.listeners.filterNull.forEach [
				LOG.info("listener :{}", it.name);
				ctx.addApplicationListener(it.name)
			]
		}
	}

}
